<script setup lang="ts">
import { useColumns } from "./columns";

import { ref, onMounted } from "vue";
import EnterpriseForm from "./EnterpriseForm.vue";
import {
  getEnterpriseInfoList,
  getEnterpriseInfoDetail,
  updateEnterpriseInfo,
  type EnterpriseInfoItem
} from "@/api/enterpriseInfo";
import { message } from "@/utils/message";
import { useUserStoreHook } from "@/store/modules/user";

defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "enterpriseInfo"
});

// 表格数据
const tableData = ref<EnterpriseInfoItem[]>([]);
// 加载状态
const loading = ref(false);
// 分页信息
const pagination = ref({
  total: 0,
  page: 1,
  limit: 10
});
// 搜索关键词
const searchKeyword = ref("");

// 获取展商信息列表
const fetchEnterpriseInfoList = async (page = 1, limit = 10, keyword = "") => {
  try {
    loading.value = true;
    // 从用户store中获取登录时使用的电话号码
    const userStore = useUserStoreHook();
    let contact_phone = userStore.contact_phone;

    // 如果store中没有电话号码，尝试从username获取（因为登录时username就是电话号码）
    if (!contact_phone && userStore.username) {
      contact_phone = userStore.username;
    }

    // 验证电话号码是否获取成功
    if (!contact_phone) {
      console.error("错误：未获取到用户电话号码，无法获取展商信息");
      message("未获取到用户信息，请重新登录", { type: "error" });
      return;
    }

    const response = await getEnterpriseInfoList(
      page,
      limit,
      contact_phone,
      keyword
    );

    if (response.code === 1) {
      tableData.value = response.data.list;
      pagination.value = {
        total: response.data.total,
        page: response.data.page,
        limit: response.data.limit
      };
    } else {
      console.error("API返回错误:", response);
      message(response.msg || "获取展商信息列表失败", { type: "error" });
    }
  } catch (error) {
    console.error("获取展商信息列表失败:", error);
    console.error("错误详情:", {
      message: error.message,
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      config: error.config
    });

    // 根据错误类型显示不同的错误信息
    if (error.response) {
      // 服务器响应了错误状态码
      if (error.response.status === 401) {
        message("未授权，请重新登录", { type: "error" });
      } else if (error.response.status === 403) {
        message("权限不足", { type: "error" });
      } else if (error.response.status === 404) {
        message("接口不存在", { type: "error" });
      } else if (error.response.status >= 500) {
        message("服务器错误，请稍后重试", { type: "error" });
      } else {
        message(
          `请求失败: ${error.response.status} ${error.response.statusText}`,
          { type: "error" }
        );
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      message("网络连接失败，请检查网络设置", { type: "error" });
    } else {
      // 其他错误
      message("获取展商信息列表失败，请稍后重试", { type: "error" });
    }
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  // 延迟一点时间确保store已经初始化
  setTimeout(() => {
    fetchEnterpriseInfoList(1, 10, "");
  }, 100);
});

// 搜索功能
const handleSearch = () => {
  pagination.value.page = 1; // 搜索时重置到第一页
  fetchEnterpriseInfoList(pagination.value.page, 10, searchKeyword.value);
};

// 分页改变
const handleCurrentChange = (page: number) => {
  pagination.value.page = page;
  fetchEnterpriseInfoList(page, 10, searchKeyword.value);
};

const handleRefresh = () => {
  // 调用列表查询接口
  fetchEnterpriseInfoList(pagination.value.page, 10, searchKeyword.value);
};

const handleView = async (row: EnterpriseInfoItem) => {
  // 处理查看逻辑
  try {
    const response = await getEnterpriseInfoDetail(row.id);
    if (response.code === 1) {
      formMode.value = "view";
      currentFormData.value = response.data;
      isShowEditDialog.value = true;
    } else {
      message(response.msg || "获取展商详情失败", { type: "error" });
    }
  } catch (error) {
    console.error("获取展商详情失败:", error);
    message("获取展商详情失败，请重试", { type: "error" });
  }
};

const handleEdit = async (row: EnterpriseInfoItem) => {
  // 检查状态，如果状态为0（待提交）或1（已通过），则不允许修改
  if (row.status === 0 || row.status === 1) {
    message("当前状态不允许修改", { type: "warning" });
    return;
  }

  // 处理修改逻辑
  try {
    const response = await getEnterpriseInfoDetail(row.id);
    if (response.code === 1) {
      formMode.value = "edit";
      currentFormData.value = response.data;
      isShowEditDialog.value = true;
    } else {
      message(response.msg || "获取展商详情失败", { type: "error" });
    }
  } catch (error) {
    console.error("获取展商详情失败:", error);
    message("获取展商详情失败，请重试", { type: "error" });
  }
};

const { columns } = useColumns(handleView, handleEdit);

const handleCancel = () => {
  isShowEditDialog.value = false;
};

const handleConfirm = async (formData?: EnterpriseInfoItem) => {
  try {
    if (formMode.value === "edit" && formData) {
      // 修改展商信息
      const result = await updateEnterpriseInfo(formData as EnterpriseInfoItem);

      if (result.code === 1) {
        message("修改展商信息成功！", { type: "success" });
        isShowEditDialog.value = false;
        // 刷新列表
        await fetchEnterpriseInfoList(
          pagination.value.page,
          10,
          searchKeyword.value
        );
      } else {
        message(result.msg || "修改展商信息失败！", { type: "error" });
      }
    } else {
      // 查看模式，直接关闭
      isShowEditDialog.value = false;
    }
  } catch (error) {
    console.error("操作失败:", error);
    message("操作失败，请重试！", { type: "error" });
  }
};

const isShowEditDialog = ref(false);
const formMode = ref<"view" | "edit">("view"); // 表单模式：查看、修改
const currentFormData = ref<EnterpriseInfoItem | null>(null); // 当前表单数据
</script>

<template>
  <div>
    <!-- 统一的白色背景容器 -->
    <div class="table-container">
      <!-- 自定义头部 -->
      <div class="custom-header">
        <div class="header-left">
          <h2 class="header-title">企业资料</h2>
        </div>
        <div class="header-right">
          <!-- 可以在这里添加按钮 -->
        </div>
      </div>

      <!-- 表格 -->
      <pure-table
        v-loading="loading"
        :data="tableData"
        :columns="columns"
        element-loading-text="加载中..."
        :scroll="{ x: 1800 }"
        style="width: 100%"
        stripe
      />

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          :page-size="10"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 弹框放在最外层，避免被其他组件影响 -->
    <div v-if="isShowEditDialog" class="myform">
      <EnterpriseForm
        :mode="formMode"
        :initial-data="currentFormData"
        @cancel="handleCancel"
        @confirm="handleConfirm"
      />
    </div>
  </div>
</template>

<style scoped>
/* 统一的白色背景容器 */
.table-container {
  background-color: #fff;
  padding: 0 20px;
}

/* 自定义头部样式 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.header-left .header-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 分页容器样式 */
.pagination-container {
  padding: 20px 0;
  text-align: center;
  display: flex;
  justify-content: center;
  width: 100%;
}

/* 搜索框样式 */
.search-box {
  display: flex;
  align-items: center;
}

/* 表格滚动条样式 */
:deep(.el-table) {
  overflow-x: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 固定列样式 */
:deep(.el-table__fixed-right) {
  box-shadow: -2px 0 8px rgb(0 0 0 / 10%);
}

:deep(.el-table__fixed) {
  box-shadow: 2px 0 8px rgb(0 0 0 / 10%);
}
</style>
